package com.hdl.design.pattern.engine.template;

import com.hdl.design.pattern.engine.facade.ReqDataToMapFacade;
import com.hdl.design.pattern.engine.strategy.ao.AoStrategy;
import com.hdl.design.pattern.engine.strategy.ao.CipLoginReqToAo;
import com.hdl.design.pattern.engine.strategy.ao.ReqToAoContext;

import java.util.Map;

/**
 * 类名 AbstractRequestHandler
 * 描述 抽象Socket请求处理器
 * 请求到响应的抽象模板
 *
 * @author hedonglin
 * @version 1.0
 * @date 2019/9/25 14:47
 */
public abstract class AbstractRequestHandler {
    private ReqDataToMapFacade reqDataToMapFacade = new ReqDataToMapFacade();
    /**
     * 方法描述: 从渠道中读取数据
     * @param msg 消息数据
     * @author hedonglin
     * @date 2019/9/25 14:49
    */
    public void channelRead0(String msg){
        // 1、将请求数据转化为Map,这里还可以得到一个是XML/JSON标志
        Map<String, Object> reqMap = reqDataToMapFacade.reqDataToMap(msg);

        // 2、将Map转化为AoMap
        Map<String, Object> aoMap = new ReqToAoContext(creAoStgyByTransCode(reqMap)).context(reqMap, null);

        // 3、调用数据服务补全AO
        System.out.println("3、调用数据服务补全AO");

        // 4、调用请求处理(引擎或ETL)
        Map<String, Object> resMap = reqHandler(reqMap, aoMap);

        // 5、将构造的返回Map转化为JSON/XML字符串
        String resStr = reqDataToMapFacade.mapToStr(resMap);

        // 6、将字符串传递给下一个Handler
        System.out.println(resStr);
    }

    // 这里可以写成一个简单工厂，通过传入交易码判断调用哪个策略
    private AoStrategy creAoStgyByTransCode(Map<String, Object> reqMap){
        String transCode = (String) reqMap.get("transCode");
        AoStrategy aoStrategy = null;
        switch (transCode){
            case "1" :
                aoStrategy = new CipLoginReqToAo();
                break;
            default:
                break;

        }
        return aoStrategy;
    }


    /**
     * 方法描述: 引擎和ETL各自的请求处理
     * @param reqMap 请求参数
     * @param aoMap 转化后的AoMap
     * @author hedonglin
     * @date 2019/9/25 15:33
     * @return {Map} 返回结果Map
    */
    public abstract Map<String, Object> reqHandler(Map<String, Object> reqMap, Map<String, Object> aoMap);

    /**
     * 渠道读取完成
     */
    public void channelReadComplete(){

    }



}
